#!/usr/bin/env bash

if [ -z $1 ] || [ $1 == '--help' ]; then
	echo 'chroot helper script for Debian'
	echo 'No mount directory specified. Mount partitions to /mnt and then run:'
	echo "  $0 /mnt"
	exit 0
fi

if [ ! -x "$(command -v apt)" ]; then
	echo 'You are not running from Debian. This script was designed to be run from Debian.'
	echo 'This may not work as expected.'
	echo 'Do you want to continue? [y/N]'
	read ans
	if [[ ! "$ans" == [Yy] ]]; then
		exit 0
	fi
fi

CHROOT_DIR=$1

if [ ! -d "$CHROOT_DIR" ]; then
	echo "The directory $CHROOT_DIR does not exist."
	echo 'Please create the directory, mount devices to it and try again.'
	exit 0
fi

if [ ! -d "$CHROOT_DIR/dev" ]; then
	echo "Debian is not probably installed yet on $CHROOT_DIR."
	echo 'Please install Debian and try again.'
	exit 0
fi


echo "Mounting and copying things to $CHROOT_DIR..."


mount -o rbind /dev "$CHROOT_DIR/dev"
mount -t proc proc "$CHROOT_DIR/proc"
mount -t sysfs sys "$CHROOT_DIR/sys"

mount -o rbind /run/lvm "$CHROOT_DIR/run/lvm"
mount -o rbind /run/lock/lvm "$CHROOT_DIR/run/lock/lvm"

cp /etc/resolv.conf "$CHROOT_DIR/etc/resolv.conf"
cp /etc/mtab "$CHROOT_DIR/etc/mtab"


echo "Running chroot on $CHROOT_DIR..."

chroot "$CHROOT_DIR" /bin/bash
